﻿(function () {
    "use strict";

    var configs;

    function showCards() {
        var i, _item, _size;

        for (i = 0; i < configs.length; i++) {
            _item = configs[i];
            _size = _item.orientations[0] == 'portrait' ? 'w=350/h=500' : 'w=500/h=350';
            configs[i].icon = configs[i].icon.replace('w=?/h=?', _size);
        }

        var cardList = new WinJS.Binding.List(configs);
        var cardListView = document.getElementById("cardListView").winControl;
        cardListView.itemDataSource = cardList.dataSource;
        cardListView.itemTemplate = document.getElementById("cardTemplate");
        cardListView.forceLayout();

        cardListView.addEventListener("iteminvoked", itemInvokedHandler, false);
    }

    function itemInvokedHandler(eventObject) {
        eventObject.detail.itemPromise.done(function (invokedItem) {
            Context.cardInfo = invokedItem.data;
            WinJS.Navigation.navigate("/pages/card/card.html");
        });
    }

    function preloadFrames() {
        var i, _item, c, o, _url, _img;

        for (i = 0; i < configs.length; i++) {
            _item = configs[i].config_map;
            for (o in _item) {
                for (c in _item[o]) {
                    _url = _item[o][c].document_root + '/' + _item[o][c].layout.overlay_ipath_print_res;
                    if (!Context.frames[_url]) {
                        _img = $('<img />');
                        _img.attr('src', _url);
                        Context.frames[_url] = _img;
                    }
                }
            }
        }
    }

    WinJS.UI.Pages.define("/pages/design/design.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
            $('span.pagetitle').text('Cards in ' + Context.name);
            var _configUrl = C.BaseURL + Context.detail.config_url + '/' + C.ConfigName;
            WinJS.xhr({
                type: 'GET',
                url: _configUrl
            }).done(function (result) {
                if (result.status === 200) {
                    configs = JSON.parse(result.responseText);
                    showCards();
                    setImmediate(preloadFrames);
                }
            }, function () { });

            var i;

            for (i = 0; i < Context.photos.length; i++) {
                console.log(Context.photos[i].el[0].src);
            }

            
        }
    });
})();
